import { defineStore } from 'pinia'
import { asyncRoutes, constantRoutes } from '@/router'
import router from './data.json'
import Layout from '@/layout/index.vue'
// import { request } from '@/utils/request'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
const generateRoutes = (routes, level = 0) => {
  const comp = import.meta.glob(`../views/*/*.vue`);
  return routes.map(route => {
    const { children = [], ...rest } = route;
    const { name = '', path = '/', redirect = '', hidden = false, meta = {} } = rest;
    if (level === 0) {
      return {
        redirect,
        path,
        component: Layout,
        hidden,
        children: generateRoutes(children, level + 1)
      };
    } else {
      const component = comp[`../${route.component}`];
      return {
        name,
        path,
        meta,
        component,
        children: children.length ? generateRoutes(children, level + 1) : undefined
      };
    }
  });
};


export const usePermissionStore = defineStore('permission', {
  state: () => {
    return {
      routes: [],
      addRoutes: []
    }
  },
  actions: {
    /**
     * @method generateRoutes 生成路由
     */
    generateRoutes(roles) {
      // console.log(import.meta)
      return new Promise((resolve) => {
        const accessedRoutes = roles.includes('admin')
          ? asyncRoutes || []
          : filterAsyncRoutes(asyncRoutes, roles)
        let routerList = generateRoutes(router);

        this.routes = constantRoutes.concat(accessedRoutes)

        // this.routes=generateRoutes(router);

        // console.log(routerList)
        // resolve(this.routes)
        resolve(accessedRoutes)

      })
    }
  }
})
